﻿using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace YQFK.Helper
{
    public class WriteLog
    {
        private static BlockingCollection<LogItem> logList = new BlockingCollection<LogItem>();
        static WriteLog()
        {
            Task.Run(() =>
            {
                foreach (var item in logList.GetConsumingEnumerable())
                {
                    try
                    {
                        string dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogFiles",  item.Type);
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        string logpath = Path.Combine(dirPath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.txt");
                        if (!System.IO.File.Exists(logpath))
                        {
                            var file = System.IO.File.Create(logpath);
                            file.Close();
                        }
                        string content = string.Format("{0} {1} \r\n", item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), item.Msg);
                        content += "------------------------------------------------------------\r\n";
                        System.IO.File.AppendAllText(logpath, content,System.Text.Encoding.UTF8);

                    }
                    catch (Exception ex)
                    {
                        System.Threading.Thread.Sleep(1000);
                        logList.Add(item);
                    }
                }
            });
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="str">日志内容</param>
        /// <param name="type">日志类型 （文件夹名称） 默认SystemError</param>
        public static void AddLog(string str, string type = "SystemError")
        {
            logList.Add(new LogItem { Msg = str, Type = type });
        }
        /// <summary>
        ///  写日志
        /// </summary>
        /// <param name="ex">错误信息</param>
        /// <param name="request">request对象</param>
        /// <param name="type">日志类型 （文件夹名称）默认SystemError</param>
        public static void AddLog(Exception ex, HttpRequest request,string type = "SystemError")
        {
            string content = string.Format("{0} {1} \r\n",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), request.Url.AbsoluteUri);
            content += "------------------------------------------------------------\r\n";
            var sss = HttpContext.Current.Request.InputStream;
            sss.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] sdfsdf = new byte[sss.Length];
            sss.Read(sdfsdf, 0, sdfsdf.Length);
            string str = System.Text.Encoding.UTF8.GetString(sdfsdf);
            content += "参数：\r\n"+ str;
            content += "------------------------------------------------------------\r\n";
            content += "错误信息：\r\n";
            content += JsonConvert.SerializeObject(ex);
            logList.Add(new LogItem { Msg = content, Type = type });
        }
    }

    public class LogItem
    {
        public LogItem()
        {
            _createTime = DateTime.Now;
        }


        private DateTime _createTime;
        public DateTime CreateTime
        {
            get { return _createTime; }
        }

        private string _Type;
        public string Type
        {
            get { return _Type; }
            set { _Type = value; ; }
        }


        private string _msg;

        public string Msg
        {
            get { return _msg; }
            set { _msg = value; }
        }

    }
}